package com.test;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskInnerUtil {

	private static ConcurrentHashMap<String, FutureTask<?>> initTask = new ConcurrentHashMap<>();

	@SuppressWarnings("unchecked")
	public static <T> T get(String mapKey, Callable<T> run){
		FutureTask<?> task = initTask.get(mapKey);
		if(task == null){
			task = new FutureTask<T>(run);
			task = initTask.putIfAbsent(mapKey, task);
			if(task == null){
				task = initTask.get(mapKey);
				task.run();
			}
		}
		try {
			return (T)task.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		} catch (ExecutionException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**更新缓存任务
	 * @param mapKey 原来的key
	 * @param newMapKey 新的key
	 * @param run
	 * @return
	 */
	public static <T> boolean update(String mapKey, String newMapKey, Callable<T> run) {
		try{
			get(newMapKey, run);
			initTask.remove(mapKey);
			return true;
		} catch (Exception e){
			return false;
		}
	}

	/**删除缓存任务
	 * @param mapKey
	 * @return
	 */
	public static boolean delete(String mapKey) {
		if(initTask.remove(mapKey) != null) {
			return true;
		}
		return false;
	}

}
